﻿using System.ComponentModel.DataAnnotations;
using System.Net;

namespace Blazor.Validators;

public class IPAddressAttribute: ValidationAttribute
{
    protected override ValidationResult? IsValid(object? value, ValidationContext validationContext)
    {
        if (value is null || string.IsNullOrWhiteSpace(value.ToString()))
        {
            ErrorMessage = ValidatorLocalization.BlankString;
            return new ValidationResult(ValidatorLocalization.BlankString);
        }

        var ipAddress = value.ToString();
        if (IPAddress.TryParse(ipAddress, out _))
        {
            return ValidationResult.Success;
        }

        ErrorMessage = ValidatorLocalization.InvalidIP;
        return new ValidationResult(ValidatorLocalization.InvalidIP);
    }
}